var md = require('md5.js');
/*
 * @Author: lnczx
 * 签名生成	
 * appkey,appsecret为常量，
 * params，传入的参数，string || object
 * 需要借助md5.js
 * 规则：将所有参数字段按首字母排序， 拼接成key1 = value1 & key2 = value2的格式，再在末尾拼接上key = appSecret， 再做MD5加密生成sign
 */
var appkey = "12123f5e6f4e122fae5b779883d0272d";
var appsecret = "59814c90f85eb7805042b46cf6901bf6";

function getSignParams(params) {
	var oncestr = createUuid();
	params.appkey = appkey;
	params.oncestr = oncestr;
	var sign = createSign(params);
	params.sign = sign;
	return params;
}

function createSign(params) {

	var arr = [];
	for ( var i in params) {
		if (params[i] != undefined && params[i].toString() != '') {
//			arr.push((i + "=" + encodeURI(params[i])));
			arr.push((i + "=" + params[i]));
		}
			
	}

	return paramsStrSort(arr.join(("&")));
}

function paramsStrSort(paramsStr) {

	var urlStr = paramsStr.split("&").sort().join("&");
	var newUrl = urlStr + '&secret=' + appsecret;
	console.log(newUrl);
	return md.md5(newUrl).toUpperCase();
}

function createUuid() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the
	// clock_seq_hi_and_reserved
	// to 01

	var uuid = s.join("");

	return uuid;
}

module.exports = {
  getSignParams: getSignParams,
  createUuid : createUuid
}